package com.ruoyi.cms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.DescribeImageModerationResultResponseBody;
import com.aliyun.green20220302.models.VideoModerationResultResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.api.feign.ContentModerationService;
import com.ruoyi.cms.entity.domain.UserMediaFile;
import com.ruoyi.cms.mapper.UserMediaFileMapper;
import com.ruoyi.cms.service.ContentModerationJobService;
import com.ruoyi.common.enums.cms.FileModerationStatusEnum;
import com.ruoyi.common.enums.cms.FileRiskLevelEnum;
import com.ruoyi.common.enums.cms.OriginalFileType;
import com.ruoyi.common.exception.modules.CmsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ContentModerationJobServiceImpl implements ContentModerationJobService {

    @Value("${ruoyi.env}")
    private String env;
    @Autowired
    private UserMediaFileMapper userMediaFileMapper;
    @Autowired
    private ContentModerationService contentModerationService;

    /**
     * 媒体内容提交审核定时任务
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void mediaModerationJob() throws Exception {
        if (env.startsWith("gpu")) {
            return;
        }
        LambdaQueryWrapper<UserMediaFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserMediaFile::getModerationStatus, FileModerationStatusEnum.NO.getStatus());
        List<UserMediaFile> list = userMediaFileMapper.selectList(queryWrapper);

        if (CollUtil.isEmpty(list)) {
            return;
        }

        Client client;
        try {
            client = contentModerationService.createSHClient();
        } catch (Exception e) {
            log.error("内容审核失败", e);
            throw new CmsException("内容审核失败");
        }

        list.forEach(userMediaFile -> {
            try {
                mediaModeration(userMediaFile, client);
            } catch (Exception e) {
                log.error("内容审核失败, id: " + userMediaFile.getId(), e);
            }
        });
    }

    /**
     * 媒体内容提交审核
     */
    @Override
    public void mediaModeration(UserMediaFile userMediaFile, Client client) throws Exception {
        log.info("开始内容审核, id: " + userMediaFile.getId());
        String taskId = "";

        if (userMediaFile.getType().equals(OriginalFileType.IMAGES.getType())) {
            taskId = contentModerationService.imageAsyncModeration(userMediaFile.getObjectName(), client);
        } else if (userMediaFile.getType().equals(OriginalFileType.VIDEO.getType())) {
            taskId = contentModerationService.videoModeration(userMediaFile.getObjectName(), client);
        }

        userMediaFile.setTaskId(taskId);
        userMediaFile.setModerationStatus(FileModerationStatusEnum.MODERATION.getStatus());
        userMediaFileMapper.updateById(userMediaFile);
    }

    /**
     * 查询媒体内容审核结果定时任务
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void moderationResultJob() throws Exception {
        if (env.startsWith("gpu")) {
            return;
        }
        LambdaQueryWrapper<UserMediaFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserMediaFile::getModerationStatus, FileModerationStatusEnum.MODERATION.getStatus());
        List<UserMediaFile> list = userMediaFileMapper.selectList(queryWrapper);

        if (CollUtil.isEmpty(list)) {
            return;
        }

        Client client;
        try {
            client = contentModerationService.createSHClient();
        } catch (Exception e) {
            log.error("内容审核失败", e);
            throw new CmsException("内容审核失败");
        }

        list.forEach(userMediaFile -> {
            try {
                mediaModerationResult(userMediaFile, client);
            } catch (Exception e) {
                log.error("内容审核失败, id: " + userMediaFile.getId(), e);
            }
        });
    }

    /**
     * 查询媒体内容审核结果
     */
    private void mediaModerationResult(UserMediaFile userMediaFile, Client client) throws Exception {
        log.info("获取内容审核结果, id: " + userMediaFile.getId());
        String riskLevel = "";
        String moderationResult = "";

        if (userMediaFile.getType().equals(OriginalFileType.IMAGES.getType())) {
            DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = contentModerationService.getImageResult(userMediaFile.getTaskId(), client);
            riskLevel = data.getRiskLevel();
            moderationResult = JSON.toJSONString(data);
        } else if (userMediaFile.getType().equals(OriginalFileType.VIDEO.getType())) {
            VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = contentModerationService.getVideoResult(userMediaFile.getTaskId(), client);
            riskLevel = data.getRiskLevel();
            moderationResult = JSON.toJSONString(data);
        }

        userMediaFile.setRiskLevel(riskLevel);

        if (FileRiskLevelEnum.HIGH.getLevel().equals(riskLevel) || FileRiskLevelEnum.MEDIUM.getLevel().equals(riskLevel)) {
            userMediaFile.setModerationStatus(FileModerationStatusEnum.NOT_PASS.getStatus());
            userMediaFile.setModerationResult(moderationResult);
        } else if (FileRiskLevelEnum.LOW.getLevel().equals(riskLevel) || FileRiskLevelEnum.NONE.getLevel().equals(riskLevel)){
            userMediaFile.setModerationStatus(FileModerationStatusEnum.PASS.getStatus());
        }

        userMediaFileMapper.updateById(userMediaFile);
    }
}
